/* 
 * Author: Pedro Faustino, software.pedrofaustino.com
 *
 * Reused code from Jan Odvarko, http://www.softwareishard.com/
 */

FBL.ns(function() { with (FBL) { 

// Constants
//-----------------------------------------------------------------------------

const Cc = Components.classes;
const Ci = Components.interfaces;


// Model implementation for listening to NetMonitor.NetRequestTable events
//-----------------------------------------------------------------------------

Firebug.NetRequestTableListenerModule = extend(Firebug.Module,
{
	dispatchName: "netRequestTableListener",
    initialize: function(owner)
    {
        Firebug.Module.initialize.apply(this, arguments);

        // Register NetMonitor.NetRequestTable listener
        this.netRequestTableListener = new NetRequestTableListener();
        Firebug.NetMonitor.NetRequestTable.addListener(this.netRequestTableListener);
    },

    shutdown: function()
    {
        Firebug.Module.shutdown.apply(this, arguments);

        // Unregister NetMonitor.NetRequestTable listener
        Firebug.NetMonitor.NetRequestTable.removeListener(this.netRequestTableListener);
    }
});


// Model Implementation for the AdAnalytics button
//-----------------------------------------------------------------------------

Firebug.AdAnalyticsButton = extend(Firebug.Module,
{
	dispatchName: "adAnalyticsButton",
	panel: null,
	isChecked: false,
	
	initialize: function()
    {
        if (FBTrace.DBG_ADANALYTICSBTN)
            FBTrace.sysout(".adanalytics.AdAnalyticsButton.initialize");

        // we listen for showUI/hideUI for panel activation
        Firebug.registerUIListener(this);
    },

    shutdown: function()
    {
        if (FBTrace.DBG_ADANALYTICSBTN)
            FBTrace.sysout(".adanalytics.AdAnalyticsButton.shutdown");

        Firebug.unregisterUIListener(this);
    },
	
	// UI Listener
    showUI: function(browser, context)
    {
		this.panel = context.getPanel(Firebug.NetMonitor.panelName, true);
		if(this.panel && this.isChecked)
		{
			setClass(this.panel.panelNode, "hideCategory-not-adAnalytics");
			if (FBTrace.DBG_NETREQUESTTABLELISTENER)
				FBTrace.sysout("adAnalyticsButton.showUI; SUCCESS adding the CSS class 'hideCategory-not-adAnalytics'", this.panel.panelNode);
		}
    },
	
	onToggle: function(context, button)
    {
        if (!context.netProgress)
            return;

        // The content filter has been changed. Make sure that the content
        // of the panel is updated (CSS is used to hide or show individual files).
        if (this.panel)
        {
            this.setFilter(button);
            //this.panel.updateSummaries(now(), true);
        }
    },

    setFilter: function(button)
    {
        var panelNode = this.panel.panelNode;
		if(button.checkState == 1)
		{
			this.isChecked = true;
			setClass(panelNode, "hideCategory-not-adAnalytics");
			if (FBTrace.DBG_ADANALYTICSBTN)
				FBTrace.sysout(".adAnalyticsButton.setFilter; showing ad analytics rows", button);
		}
		else
		{
			this.isChecked = false;
			removeClass(panelNode, "hideCategory-not-adAnalytics");
			if (FBTrace.DBG_ADANALYTICSBTN)
				FBTrace.sysout(".adAnalyticsButton.setFilter; hiding ad analytics rows", button);
		}
    }

});


// Model Implementation for the AdAnalytics tab
//-----------------------------------------------------------------------------

Firebug.AdAnalyticsTab = extend(Firebug.Module, 
{
	dispatchName: "adAnalyticsTab",
    initialize: function()
    {
        if (FBTrace.DBG_ADANALYTICSTAB)
            FBTrace.sysout(".adanalytics.AdAnalyticsTab.initialize");

        Firebug.NetMonitor.NetInfoBody.addListener(this);
    },

    shutdown: function()
    {
        if (FBTrace.DBG_ADANALYTICSTAB)
            FBTrace.sysout(".adanalytics.AdAnalyticsTab.shutdown");

        Firebug.NetMonitor.NetInfoBody.removeListener(this);
    },

    // Listener for NetInfoBody.
    initTabBody: function(infoBox, file)
    {
        if (FBTrace.DBG_ADANALYTICSTAB)
            FBTrace.sysout(".adanalytics.AdAnalyticsTab.initTabBody", infoBox);

        if (file.category == "html")
            Firebug.NetMonitor.NetInfoBody.appendTab(infoBox, "AdAnalytics", 
                this.$STR("adanalytics.tab.title"));
    },

    destroyTabBody: function(infoBox, file)
    {
        if (FBTrace.DBG_ADANALYTICSTAB)
            FBTrace.sysout(".adanalytics.AdAnalyticsTab.destroyTabBody");
    },

    updateTabBody: function(infoBox, file, context)
    {
        // Get currently selected tab.
        var tab = infoBox.selectedTab;

        if (FBTrace.DBG_ADANALYTICSTAB)
            FBTrace.sysout(".adanalytics.AdAnalyticsTab.updateTabBody: " + tab.innerHTML);

        // Generate content only for the first time; and only if our tab 
        // has been just activated.
        if (tab.dataPresented || !hasClass(tab, "netInfoAdAnalyticsTab"))
            return;

        // Make sure the content is generated just once.
        tab.dataPresented = true;

        // Get body element associated with the tab.
        var tabBody = getElementByClass(infoBox, "netInfoAdAnalyticsText");

        // Get response data from Firebug's cache.
        var responseText = context.sourceCache.loadText(file.href);

        // Parse response and create DOM.
        var parser = CCIN("@mozilla.org/xmlextras/domparser;1", "nsIDOMParser")
        var doc = parser.parseFromString(responseText, "text/xml");
        var root = doc.documentElement;

        // Error handling
        var nsURI = "http://www.mozilla.org/newlayout/xml/parsererror.xml";
        if (root.namespaceURI == nsURI && root.nodeName == "parsererror") 
        {
            Firebug.AdAnalyticsTab.ParseError.tag.replace({error: {
                message: root.firstChild.nodeValue,
                source: root.lastChild.textContent
            }}, tabBody);
            return;
        }

        // Generate UI using Domplate template (from HTML panel).
        Firebug.HTMLPanel.CompleteElement.tag.replace({object: root}, tabBody);
    },

    // CSS helper
    addStyleSheet: function(panel)
    {
        // Make sure the stylesheet isn't appended twice. 
        var doc = panel.document;
        if ($("adAnalyticsStyles", doc))
            return;
        
        var styleSheet = createStyleSheet(doc, "chrome://adanalytics/skin/adAnalytics.css");
        styleSheet.setAttribute("id", "adAnalyticsStyles");
	    addStyleSheet(doc, styleSheet);
    },

    showPanel: function(browser, panel) 
    { 
        if (panel && panel.name == Firebug.NetMonitor.panelName)
            this.addStyleSheet(panel);       
    },

    $STR: function(name)
    {
        return document.getElementById("strings_adAnalytics").getString(name);
    }
}); 


// Net Panel listener
//-----------------------------------------------------------------------------

function NetRequestTableListener() {}

NetRequestTableListener.prototype = 
{

    onCreateRequestEntry: function(context, row)
    {
		try
		{
			var file = row.repObject;
			var hostname = file.request.originalURI.host;
			if(hostname.search(/oas.five.tv/) != -1 ) {
				setClass(row, "category-adAnalytics");
				if (FBTrace.DBG_NETREQUESTTABLELISTENER)
					FBTrace.sysout("netRequestTableListener.onCreateRequestEntry; SUCCESS adding the CSS class 'category-adAnalytics' to file.href=" + file.href, file);
			}
			else
			{
				setClass(row, "category-not-adAnalytics");
				if (FBTrace.DBG_NETREQUESTTABLELISTENER)
					FBTrace.sysout("netRequestTableListener.onCreateRequestEntry; SUCCESS adding the CSS class 'category-not-adAnalytics' to file.href=" + file.href, file);
			}
		}
		catch (err)
		{
			if (FBTrace.DBG_NETREQUESTTABLELISTENER || FBTRace.DBG_ERRORS)
				FBTrace.sysout("netRequestTableListener.onCreateRequestEntry; EXCEPTION", err);
		}
		
		if (FBTrace.DBG_NETREQUESTTABLELISTENER)
            FBTrace.sysout("netRequestTableListener.onCreateRequestEntry; " + (file ? file.href : ""));
		
    }
};


// XML Parsing message template
//-----------------------------------------------------------------------------

Firebug.AdAnalyticsTab.ParseError = domplate(Firebug.Rep, 
{
    tag:
        DIV({class: "adAnalyticsError"},
            DIV({class: "adAnalyticsErrorMsg"}, "$error.message"),
            PRE({class: "adAnalyticsErrorSource"}, "$error|getSource")
        ),
    
    getSource: function(error) 
    {
        var parts = error.source.split("\n");
        if (parts.length != 2)
            return error.source;

        var limit = 50;
        var column = parts[1].length;
        if (column >= limit) {
            parts[0] = "..." + parts[0].substr(column - limit);
            parts[1] = "..." + parts[1].substr(column - limit);
        }

        if (parts[0].length > 80)
            parts[0] = parts[0].substr(0, 80) + "...";

        return parts.join("\n");
    }
});

// Registration
//-----------------------------------------------------------------------------

Firebug.registerModule(Firebug.AdAnalyticsButton);
Firebug.registerModule(Firebug.AdAnalyticsTab);
Firebug.registerModule(Firebug.NetRequestTableListenerModule);

}});
